package net.chenlin.dp.common.oauth2;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import net.chenlin.dp.common.utils.ShiroUtils;
import net.chenlin.dp.modules.sys.entity.SysUserEntity;

/**
 * 认证
 *
 * @author ZhouChenglin
 * @email yczclcn@163.com
 * @url www.chenlintech.com
 * @date 2017年9月3日 上午3:24:29
 */
@Component
public class OAuth2Realm extends AuthorizingRealm {

	@Override
	public boolean supports(AuthenticationToken token) {
		return token instanceof OAuth2Token;
	}

	/**
	 * 授权(验证权限时调用) 
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		
		//会进入授权方法一共有三种情况！ 
		// 1、subject.hasRole(“admin”)或subject.isPermitted(“admin”)：自己去调用这个是否有什么角色或者是否有什么权限的时候；
		// 2、@RequiresRoles("admin") ：在方法上加注解的时候； 
		// 3、[@shiro.hasPermission name ="admin"][/@shiro.hasPermission]：在页面上加shiro标签的时候，即进这个页面的时候扫描到有这个标签的时候。
	
		Long userId = ShiroUtils.getUserId();
		// 用户角色
		List<String> roles = Arrays.asList(new String[] { "hello", "role1" });
		Set<String> rolesSet = new HashSet<>();
		for (String role : roles) {
			if (StringUtils.isNotBlank(role)) {
				rolesSet.addAll(Arrays.asList(role.trim().split(",")));
			}
		}
		// 用户权限
		List<String> perms = Arrays.asList(new String[] { "admin:sys:user", "ook:hello:123" });
		Set<String> permsSet = new HashSet<>();
		for (String perm : perms) {
			if (StringUtils.isNotBlank(perm)) {
				permsSet.addAll(Arrays.asList(perm.trim().split(",")));
			}
		}
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.setRoles(rolesSet);
		info.setStringPermissions(permsSet);

		System.out.println("doGetAuthorizationInfo-----YYYYYYYYY");

		return info;
	}

	/**
	 * 认证(登录时调用)
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String accessToken = (String) token.getPrincipal();
		// 查询用户信息
		SysUserEntity user = new SysUserEntity();
		user.setUserId(1000L);
		user.setUsername("fanzhicheng");

		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, accessToken, getName());

		System.out.println("doGetAuthenticationInfo--XXXXXXXXXXX");

		return info;
	}
}
